package com.bnlr.lrparking.appui.bank;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.bnlr.lrparking.app.Application;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.appui.web.WebActivity;
import com.bnlr.lrparking.base.BaseActivity;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.constant.LrConstant;
import com.bnlr.lrparking.constant.Urls;
import com.bnlr.lrparking.event.AddBankCardSucceeEvent;
import com.bnlr.lrparking.model.BaseArrayBean;
import com.bnlr.lrparking.model.VerifyCodeM;
import com.bnlr.lrparking.util.CountDownTimerUtils;
import com.bnlr.lrparking.view.ClearEditText;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.rest.Request;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by hp on 2017/8/31.
 * 添加银行卡
 */
public class AddBankCardTwoActivity extends BaseActivity {

    private TextView tvNavTitle;
    private EditText ed_phone;
    String bankName="";
    private TextView tv_addbankcard_btn2,ed_bankname,tv_clause;
    private String bankNo,bankUser;
    private CheckBox checkBox;
    private RelativeLayout rl_agree;
    private Unbinder unbinder;
    @BindView(R.id.tv_verifica)
    TextView tvVerify;
    @BindView(R.id.et_verify)
    ClearEditText etVerify;
    CountDownTimerUtils mCountDownTimerUtils;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addbankcardtwo);
        unbinder = ButterKnife.bind(this);
        initView();
    }

    private void initView(){
        EventBus.getDefault().register(this);//
        tvNavTitle=(TextView)findViewById(R.id.tv_nav_title);
        tvNavTitle.setText("填写银行卡信息");
        ed_phone=(EditText)findViewById(R.id.ed_phone);
        tv_addbankcard_btn2=(TextView)findViewById(R.id.tv_addbankcard_btn2);
        ed_bankname=(TextView)findViewById(R.id.ed_bankname);
        tv_clause = (TextView) findViewById(R.id.tv_clause);
        checkBox = (CheckBox) findViewById(R.id.agree_clause);
        rl_agree = (RelativeLayout) findViewById(R.id.rl_agree);
        Intent intent=getIntent();
        bankName=intent.getStringExtra("bankType");
        bankNo = intent.getStringExtra("bankNo");
        bankUser = intent.getStringExtra("bankUser");
        ed_bankname.setText(bankName);
        ed_phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (isMobileNO(ed_phone.getText().toString()) && !checkBox.isChecked()) {
                    changeState(true);
                    tvVerify.setEnabled(true);
                } else {
                    changeState(false);
                    tvVerify.setEnabled(false);
                }
            }
        });
        tv_addbankcard_btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(etVerify.getText().toString())) {
                    etVerify.setShakeAnimation();
                    return;
                }
                addBank();
            }
        });
        tv_clause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(baseContext,WebActivity.class);
                intent.putExtra("tag",3);
                startActivity(intent);
            }
        });
        rl_agree.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkBox.isChecked()) {
                    checkBox.setChecked(false);
                    if (isMobileNO(ed_phone.getText().toString())) {
                        changeState(true);

                    }
                } else {
                    checkBox.setChecked(true);
                    changeState(false);
                }
            }
        });
        tvVerify.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SendYzm();
            }
        });
    }
    private void SendYzm() {
        try {
            mRequest = NoHttp.createStringRequest(Urls.IP, LrConstant.POST);
            mRequest.add("action", "sendValidateMCD");
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("phone", ed_phone.getText().toString());
            mRequest.add("flag", "0");
            // 添加到请求队列
            CallServer.getRequestInstance().add(AddBankCardTwoActivity.this, mRequest,
                    new CustomHttpListener<VerifyCodeM>(AddBankCardTwoActivity.this, true, VerifyCodeM.class) {
                        @Override
                        public void doWork(VerifyCodeM data, String code) {
                        }
                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {

                            try {//{"msgcode":"1","msg":"成功","data":{"code":"06641"}}
                                super.onFinally(obj, code, isSucceed);
                                if ("1".equals(code)) {
                                    setVerifica(tvVerify);
                                } else {
                                    ToastUtils.showShort(obj.getString("msg"));
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, true);
        } catch (Exception e) {

        }
    }
    //60秒的倒计时
    private void setVerifica(TextView verifica){
        mCountDownTimerUtils = new CountDownTimerUtils(verifica, 60000, 1000);
        mCountDownTimerUtils.start();
    }
    /**
     * 添加银行卡
     */
    private void addBank() {
        try {
            mRequest = NoHttp.createStringRequest(Urls.NEW_IP, LrConstant.POST);
            mRequest.add("action", "AddUserBank");
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("AccountNo",bankNo);
            mRequest.add("Mobile",ed_phone.getText().toString());
            mRequest.add("RealName",bankUser);
            mRequest.add("code",etVerify.getText().toString());
            mRequest.add("SubBankName",getIntent().getStringExtra("bankaddress"));

            CallServer.getRequestInstance().add(baseContext, mRequest,
                    new CustomHttpListener<BaseArrayBean>(baseContext, true, BaseArrayBean.class) {
                        @Override
                        public void doWork(BaseArrayBean data, String code) {
                            if (code.equals("1")) {
                                startActivity(AddBankCardSucceedActivity.class);
                            }
                        }
                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                                try {
                                    super.onFinally(obj, code, isSucceed);
                                    if (!code.equals("1")) {
                                        ToastUtils.showShort(obj.getString("msg"));
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                        }
                    }, true);
        } catch (Exception e) {

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onBankCardSucceeEvent(AddBankCardSucceeEvent event) {
        finish();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mCountDownTimerUtils != null) {
            mCountDownTimerUtils.cancel();
        }
        EventBus.getDefault().unregister(this);
        unbinder.unbind();
    }
    public void changeState (boolean isChange) {
        if (isChange) {
            tv_addbankcard_btn2.setEnabled(isChange);
            tv_addbankcard_btn2.setBackgroundResource(R.drawable.seletor_login_btn);
        } else {
            tv_addbankcard_btn2.setEnabled(isChange);
            tv_addbankcard_btn2.setBackgroundResource(R.mipmap.login_disabled);
        }
    }

    /**
     * 验证码请求
     */
    public Request<String> mRequest;
    //判断是否为电话号码
    public static boolean isMobileNO(String mobiles) {
        String telRegex = "[1][34578]\\d{9}";
        if (TextUtils.isEmpty(mobiles)) {
            return false;
        }else{
            return mobiles.matches(telRegex);
        }
    }
}
